<template>
  <div class="new-clue-detail">
    <div class="header-titles"> 线索 </div>
    <div class="header-btn flex justify-around items-center mb-12px">
      <div class="btn-left">
        <span> {{ clueValue?.name }}</span>
        <div class="ml-16px flex items-center">
          <div class="h-32px w-26px flex justify-center items-center next-prod">
            <el-button
              @click="emit('prev')"
              style="border: none; padding: 0; width: 100%"
              :disabled="isLoad"
            >
              <el-icon size="14"><ArrowLeftBold /></el-icon>
            </el-button>
          </div>
          <div class="ml-8px h-32px w-26px flex justify-center items-center next-prod">
            <el-button
              @click="emit('next')"
              style="border: none; padding: 0; width: 100%"
              :disabled="isLoad"
            >
              <el-icon size="14"><ArrowRightBold /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
      <div class="btn-right">
        <!-- 编辑 -->
        <el-button
          v-if="validateWrite"
          type="primary"
          style="background-color: #0052cc"
          v-hasPermi="['crm:clue:update']"
          @click="openForm"
        >
          <el-icon color="mr-6px" size="14"><Edit /></el-icon>
          编辑
        </el-button>
        <!-- 转移 -->
        <el-tooltip
          class="box-item"
          effect="dark"
          content="转移"
          placement="top"
          v-if="validateOwnerUser"
        >
          <el-button style="background-color: #ebecf0" class="!p-8px" @click="transfer">
            <el-icon color="#4b5a74" size="14"><Switch /></el-icon>
          </el-button>
        </el-tooltip>
        <!-- 转客户 -->
        <el-tooltip
          v-if="!clueValue.transformStatus && validateOwnerUser"
          class="box-item"
          effect="dark"
          content="转客户"
          placement="top"
        >
          <el-button style="background-color: #ebecf0" class="!p-8px" @click="handleTransform">
            <el-icon color="#4b5a74" size="14"><UserFilled /></el-icon>
          </el-button>
        </el-tooltip>

        <el-tooltip
          v-if="clueValue.transformStatus && validateOwnerUser"
          class="box-item"
          effect="dark"
          content="已客户"
          placement="top"
        >
          <el-button style="background-color: #ebecf0" class="!p-8px">
            <el-icon color="#4b5a74" size="14"><UserFilled /></el-icon>
          </el-button>
        </el-tooltip>
        <!-- 放入公海 -->
        <el-tooltip
          class="box-item"
          effect="dark"
          content="放入公海"
          placement="top"
          v-if="validateOwnerUser"
        >
          <el-button style="background-color: #ebecf0" class="!p-8px" @click="handlePutPool">
            <el-icon color="#4b5a74" size="14"><Grid /></el-icon>
          </el-button>
        </el-tooltip>
        <!-- 领取 -->
        <el-tooltip
          class="box-item"
          effect="dark"
          content="领取"
          placement="top"
          v-if="isPool && !clueValue.ownerUserId"
        >
          <el-button
            v-hasPermi="['crm:clue:delete']"
            style="background-color: #ebecf0"
            class="!p-8px"
            @click="handleReceive"
          >
            <el-icon color="#4b5a74" size="14"><UserFilled /></el-icon>
          </el-button>
        </el-tooltip>
        <!-- 删除 -->
        <el-tooltip class="box-item" effect="dark" content="删除" placement="top">
          <el-button
            v-hasPermi="['crm:clue:delete']"
            style="background-color: #ebecf0"
            class="!p-8px"
            @click="delClue"
          >
            <el-icon color="#4b5a74" size="14"><Delete /></el-icon>
          </el-button>
        </el-tooltip>
      </div>
    </div>
    <div class="flex items-center lab-x">
      <div class="labels"> 线索来源: </div>
      <div class="cen">
        <dict-tag :type="DICT_TYPE.CRM_CUSTOMER_SOURCE" :value="clueValue.source"
      /></div>
    </div>
    <div class="flex items-center lab-x">
      <div class="labels"> 手机: </div>
      <div class="cen">
        <el-link v-if="clueValue.mobile" @click="onCall(clueValue, clueValue.mobile)"
          >{{ clueValue.encryptMobile }} <Icon class="ml-5px" icon="ep:phone" />
        </el-link>
      </div>
    </div>
    <div class="flex items-center lab-x">
      <div class="labels"> 负责人: </div>
      <div class="cen">{{ clueValue.ownerUserName }}</div>
    </div>
    <div class="flex items-center lab-x">
      <div class="labels"> 创建人: </div>
      <div class="cen">{{ clueValue.creatorName }}</div>
    </div>
    <div class="flex items-center lab-x" v-if="getModuleName(clueValue.moduleId)">
      <div class="labels"> 所属模块: </div>
      <div class="cen">
        <el-tag type="primary">{{ getModuleName(clueValue.moduleId).name }}</el-tag>
      </div>
    </div>
    <div class="flex items-center lab-x flex-wrap">
      <el-check-tag
        v-for="tag in clueValue.labelList"
        :key="tag.id"
        :style="{
          background: tag.bgColor,
          color: tag.textColor,
          marginRight: '4px'
        }"
        class="mb-4px inline-block"
        checked
      >
        {{ tag.name }}
      </el-check-tag>

      <el-popover placement="bottom" :width="300" trigger="click" title="编辑标签">
        <template #reference>
          <el-icon size="14" color="#42526e" style="cursor: pointer">
            <el-tooltip class="box-item" effect="dark" content="编辑标签" placement="top">
              <Paperclip />
            </el-tooltip>
          </el-icon>
        </template>
        <div>
          <div class="h-200px tag-content" style="overflow-y: auto">
            <div v-for="group in tagMap" :key="group.name">
              <div class="group-name">{{ group.name }}</div>
              <div>
                <el-tag
                  @click="changeTag(item.id)"
                  type="info"
                  class="mr-10px"
                  style="cursor: pointer"
                  :style="{
                    background: tagValue.indexOf(item.id) != -1 ? item.bgColor : '',
                    color: tagValue.indexOf(item.id) != -1 ? item.textColor : ''
                  }"
                  v-for="item in group?.labelList"
                  :key="item.id"
                  >{{ item.name }}</el-tag
                >
              </div>
            </div>
          </div>
          <div class="mt-10px pt-10px flex justify-end" style="border-top: 1px solid #dfe1e6">
            <el-button type="primary" @click="submit" :disabled="isLoading">确定</el-button>
          </div>
        </div>
      </el-popover>
    </div>
  </div>
  <ClueForm ref="formRef" @success="getClue" />
  <CrmTransferForm ref="transferFormRef" @success="emit('closeDrawer')" />
</template>
<script setup>
import { DICT_TYPE } from '@/utils/dict'
import ClueForm from '@/views/crm/clue/ClueForm.vue'
import CrmTransferForm from '@/views/crm/permission/components/TransferForm.vue'
import * as ClueApi from '@/api/crm/clue'
import PermissionList from '@/views/crm/permission/components/PermissionList.vue'
import * as CluePoolApi from '@/api/crm/cluePool'
import { useSoftPhoneStore } from '@/store/modules/softPhone'
import { usePhoneStore } from '@/store/modules/phone'
import { emitter } from '@/utils/eventBus.ts'

const useStore = usePhoneStore()
const useSoftPhone = useSoftPhoneStore()
const permissionListRef = ref(PermissionList)
const message = useMessage()
import {
  ArrowLeftBold,
  ArrowRightBold,
  Edit,
  Switch,
  UserFilled,
  Grid,
  Delete,
  Paperclip
} from '@element-plus/icons-vue'

const tagValue = ref([])
const props = defineProps({
  clueValue: Object,
  tagMap: Array,
  isLoad: Boolean,
  isPool: Boolean,
  validateWrite: Boolean,
  validateOwnerUser: Boolean,
  moduleOption: Array
})
watch(
  () => props.clueValue,
  (val) => {
    tagValue.value = val.labelList.map((item) => item.id)
  },
  { deep: true }
)
const emit = defineEmits(['getClueValue', 'closeDrawer', 'refreshPage', 'prev', 'next'])
/*call*/
const onCall = (row, callee) => {
  emitter.emit('simCall', {
    callee,
    source: 'clue',
    sourceId: row.id
  })
  emitter.emit('userCallCallee', callee)
}
/**重新获取线索详情*/
const getClue = () => {
  emit('getClueValue')
}
/**编辑*/
const formRef = ref()
const openForm = () => {
  formRef.value?.open('update', props.clueValue.id)
}
/** 线索转移 */
const transferFormRef = ref()
const transfer = () => {
  transferFormRef.value?.open(false, '线索转移', props.clueValue.id, ClueApi.transferClue)
}
/** 转化为客户 */
const handleTransform = async () => {
  await message.confirm(`确定将【${props.clueValue.name}】转化为客户吗？`)
  await ClueApi.transformClue(props.clueValue.id)
  message.success(`转化客户【${props.clueValue.name}】成功`)
  emit('closeDrawer')
  emit('refreshPage')
}
/** 线索放入公海 */
const handlePutPool = async () => {
  await message.confirm(`确定将【${props.clueValue.name}】放入公海吗？`)
  await ClueApi.putCluePool(unref(props.clueValue.id))
  message.success(`【${props.clueValue.name}】放入公海成功`)
  emit('closeDrawer')
  emit('refreshPage')
}
/**删除线索*/
const delClue = async () => {
  await message.confirm(`确定要删除此线索吗？`)
  if (props.isPool) {
    await CluePoolApi.deleteClueFromPool(props.clueValue.id)
  } else {
    await ClueApi.deleteClue(props.clueValue.id)
  }
  message.success('删除成功')
  emit('closeDrawer')
  emit('refreshPage')
}
/**领取线索*/
const handleReceive = async () => {
  await message.confirm(`确定领取线索【${props.clueValue.name}】 吗？`)
  await CluePoolApi.receiveClue([unref(props.clueValue.id)])
  message.success(`领取线索【${props.clueValue.name}】成功`)
  emit('closeDrawer')
  emit('refreshPage')
}
/**选择取消标签**/
const changeTag = (id) => {
  const index = tagValue.value.indexOf(id)
  if (index != -1) {
    tagValue.value.splice(index, 1)
  } else {
    tagValue.value.push(id)
  }
}
const isLoading = ref(false)
/**编辑标签*/
const submit = async () => {
  try {
    isLoading.value = true
    let obj = {
      clueId: props.clueValue.id,
      labelList: tagValue.value
    }
    await ClueApi.updateClueTag(obj)
    ElMessage.success('操作成功')
    getClue()
    emit('refreshPage')
  } finally {
    isLoading.value = false
  }
}
const getModuleName = (id) => {
  if (props.moduleOption) {
    return props.moduleOption.find((item) => item.id == id)
  }
}
</script>
<style scoped>
.new-clue-detail {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px #172b4d1a;
  margin: 0 8px;
  padding: 16px;
  margin-bottom: 20px;
  .header-titles {
    color: #6b778c;
    font-size: 14px;
    margin-bottom: 2px;
  }
  .header-btn {
    .btn-left {
      color: #172b4d;
      flex: 1;
      font-size: 24px;
      font-weight: 700;
      overflow: hidden;
      text-overflow: ellipsis;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;
      display: flex;
      align-items: center;
    }
    .btn-right {
      flex: 1;
      display: flex;
      justify-content: flex-end;
      align-items: center;
    }
  }
}
.next-prod {
  cursor: pointer;
}
.next-prod:hover {
  background-color: #f5f7fa;
}
.labels {
  color: #6b778c;
  margin-right: 8px;
  font-size: 14px;
}
.lab-x {
  line-height: 24px;
}
.cen {
  color: #172b4d;
  font-size: 14px;
}
.group-name {
  font-size: 14px;
  color: #42526e;
  font-size: 14px;
  margin: 8px 0;
}
.tag-content {
  &::-webkit-scrollbar {
    width: 2px;
  }
  &::-webkit-scrollbar-track {
    background: #f1f1f1;
  }
  &::-webkit-scrollbar-thumb {
    background: #d8d8d8;
  }
  &::-webkit-scrollbar-thumb:hover {
    background: #d8d8d8;
  }
  &::-webkit-scrollbar-thumb:horizontal:start {
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
  }
  &::-webkit-scrollbar-thumb:horizontal:end {
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
  }
}
</style>
